/*
 * uscore.js
 * Copyright(c) 2012 caih
 *
 */

//websocket
var ws = null;
var target='ws://' + window.location.host+'/examples/websocket/echoMessage';
var g_Data=[{"tag":"pscada.tag1","v":1,"s":128},{"tag":"pscada.tag2","v":1,"s":128}];
//core
var reqStr='["pscada.kg.val","pscada.kg1.val"] ';
var dataStr= '[{"tag":"pscada.kg.val","val":"1","state":"128"},{"tag":"pscada.kg1.val","val":"0","state":"128"}] ';
var g_ColorSets={	"di_color": {"v0":{"lc":"#000000","fc":"#002500"},"v1":{"lc":"#FFFF00","fc":"#0FF000"}},	"ai_color": {"v1":{"lc":1231,"fc":666},"v2":{"lc":31,"fc":66}}		 };
//ui
var g_Timer;
var g_AnimObjs=[];
var g_TagAnims=[];
var g_AnimType=["anim_gen","anim_moveh","anim_movev"];
var g_Count=0;
 //base function
 function CallService(add,para,callBackFun)
{
	serviceBacked = 0;
	$.ajax({
		url:"http://192.1.101.150:8080/Hmi/services/" + add + para,
		type:"GET",
		data:"{612000473}",
		contentType:"application/json;charset=utf-8",
		dataType:"json",
		success :function (msg){
			retValue = new String(msg.vs);
			serviceBacked = 1;
			callBackFun(retValue);
		},
        error:   function (){alert("service back error!");}
	});
}
 
 ////////////////////////
function connect() 
{            
	if ('WebSocket' in window) 
	{
		ws = new WebSocket(target);
	} 
	else if ('MozWebSocket' in window) 
	{
		ws = new MozWebSocket(target);
	} 
	else 
	{
		alert('WebSocket is not supported by this browser.');
		return;
  };
  
	ws.onopen = function () 
	{
     log('Info: WebSocket connection opened.');
      sendMsg( "----ok---");
  };
	ws.onmessage = function (event) 
	{
		g_Data=event.data;
		log('Received-----: ' + event.data);
	};
	ws.onclose = function () 
	{
		log('Info: WebSocket connection closed.');
	};
}

function disconnect() 
{
	if (ws != null) 
	{
		ws.close();
		ws = null;
	}          
}

function sendMsg(msg) 
{
  if (ws != null)
  {
     log('Sent: ' + msg);
     ws.send(msg);
  } 
  else
  {
     alert('WebSocket connection not established, please connect.');
  }
}

function log(message) 
{
	console.log(message);
}


////////////////////////////////////////////
 function HtmlEncode(s)
{
	if (s==null) return s;
	var ret =s.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
	return ret;
}
function HtmlDecode(s)
{    
  	if (s==null) return s;
  	var ret = s.replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&quot;/g, '"').replace(/&amp;/g, '&');    
  	return ret;
}

function animObj(item,type,info)
{
	var tags=new Array();//[{"tag":"pscada.tag1","value":"0","statue":"128"},{"tag":"pscada.tag2","value":"1","statue":"228"}];
	      // tags={"pscada.tag1","value":"0","statue":"128"},{"tag":"pscada.tag2","value":"1","statue":"228"}];
	var gg=HtmlDecode(info);
	var obj=JSON.parse(gg);
	this.item=item; 
	this.type=type;
	var tmp= obj.src.split(";"); //map
	for(var i=0;i<tmp.length;i++) 
	{
		tags.push({"tag":tmp[i],"value":"0","statue":"0"});
	}
	this.tags=tags;
	this.func=obj.fun;
	this.colSet=obj.colSet;
	this.changed=false;
	this.su=obj.su;
	this.sd=obj.sd;
	this.du=obj.du;
	this.dd=obj.dd;
	this.flag=obj.flag;
	this.if_tinkle=false;
        
	this.setData = function(tag,v,s){
		this.changed=true;
		return this.changed;
	};
	this.doFunc = function(){
		var tmpfun=this.func;
		if (tmpfun==undefined || tmpfun.length==0)
		{
			if(tags.length>0)
				return tags[0].value;
			Else
				return "";
		}
		var paras=[];
		var i=0;
		for(var loop=0;loop<tags.length;loop++)
		{
			var val=tags[loop].value;
			if( isNaN(tags[loop].value)==false)
				val=parseFloat(val);
			paras.push(val);
		}
            
		var ret=eval("var func="+this.func);
		ret=func.apply(this.item,paras);
		return ret;
	};
	this.advance=function(){
		if(this.if_tinkle)
		{
			this.item.toggle();
		}
		
	};
	this.render = function(){
		var log_val=this.doFunc();
 		var itemName=this.item[0].tagName;	
		if(itemName=="text")
		{
 			this.item.text(log_val);
		}        		
		if(type=="anim_gen")
		{
			var color=this.colSet;
			var lc=g_ColorSets[color]["v"+log_val]["lc"];
			var fc=g_ColorSets[color]["v"+log_val]["fc"];
			this.if_tinkle=g_ColorSets[color]["v"+log_val]["if_tinkle"];
			if(lc)
			{
				this.item.attr({"stroke":lc,"fill":fc});
		  }

 		}
 		else if(type=="anim_moveh")
 		{
 		}
	};
}

///main
(function(){
	alert("init------------");
	window.onload = init;
})()

function setColorCfg(value)
{
}

function init()
{	 
	 CallService("hdbService/getAllCfgName","",setColorCfg);
	 $("svg *").each(function(){
  	 if($(this).attr("id")!= undefined)
  	 {  	 
  	 	//var hh=$(this)[0].tagName;	
  	 	// hh=this.tagName;	
  	 		for(var type in g_AnimType)
  	 		{
  	 		 	var anim=$(this).attr(g_AnimType[type]);  	 	 
  	 			if(anim== undefined) continue;
					
  	 			var obj=new animObj($(this),g_AnimType[type],anim); 
  	 			g_AnimObjs.push(obj); 
  	 			for(var i=0;i<obj.tags.length;i++) 
        	{
        			var tag=obj.tags[i].tag;
        			if(g_TagAnims[tag]== undefined)
        				g_TagAnims[tag]=new Array();        		
        			g_TagAnims[tag].push(obj);
        	}	 		
  	 		} 
     }
  });
  
  onTimer(); 
}

function onTimer()
{
	if(g_Count%30==0)
		sendReq();
	
	if(g_Count%2==0)
		render();
		
	advance();
	//g_data=[];
	g_Timer=setTimeout("onTimer()",500);
	g_Count++;
	if(g_Count>99999)
		g_Count=0;
}

function sendReq()
{
	var req=[];
	for(var i=0;i<g_TagAnims.length;i++) 
	{

		req.push(g_TagAnims[i]);
	}	 	
	sendMsg(req);
}

function render()
{
	console.log("---render()");
	var tmpAnims=new Array();
	for(var i=0;i<g_Data.length;i++)
	{
		var tag=g_Data[i].tag;
		if(g_TagAnims[tag]== undefined) continue;
    var anims=g_TagAnims[tag];  
    for(var j=0;j<anims.length;j++)
    {
    	anims[j].setData(tag,g_Data[i].v,g_Data[i].s);
    	//tmpAnims.push(anims[j]);
    }
	}
	
  for(var i=0;i<g_AnimObjs.length;i++)
  {
    if(g_AnimObjs[i].changed)
    	g_AnimObjs[i].render();
  }	

}

function advance()
{
	for(var i=0;i<g_AnimObjs.length;i++)
  {
    	g_AnimObjs[i].advance();
  }	
}
 